package org.example;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.example.entity.whlgd.Role;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class HttpRequestExample1 {


    //定时请求
    public static void main(String[] args) {
        ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);

        Runnable task = () -> {
            try {
                // 实例化 ObjectMapper
                ObjectMapper objectMapper = new ObjectMapper();
                // 请求 URL
                String url = "https://wljy.whut.edu.cn/APermission/loadtree.ajax?searchValue=";
                // 调用 getRoles 方法
                ArrayList<Role> roles = HttpRequestExample1.getRoles(objectMapper, url);
                System.out.println(roles);
            } catch (Exception e) {
                e.printStackTrace();
            }
        };

        // 调度任务，每 30 分钟执行一次
        scheduler.scheduleAtFixedRate(task, 0, 30, TimeUnit.MINUTES);
    }

    private static ArrayList<Role> getRoles(ObjectMapper objectMapper, String url) throws Exception {
        // 自定义请求头
        Map<String, String> headers1 = new HashMap<>();
        headers1.put("Accept", "application/json, text/javascript, */*; q=0.01");
        headers1.put("Accept-Encoding", "gzip, deflate, br, zstd");
        headers1.put("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6");
        headers1.put("Cache-Control", "no-cache");
        headers1.put("Connection", "keep-alive");
        headers1.put("Content-Type", "application/x-www-form-urlencoded");
        headers1.put("Cookie", "USERLOGIN_USERNAME_COOKIE=wukaikui; USERLOGIN_USERPWD_COOKIE=IyQlcjY3OFkt; USERLOGIN_USERORG_COOKIE=00; USERLOGIN_USERLANG_COOKIE=\"\"; JSESSIONID=83326E2743E2F8928C433F93D709AB55");
        headers1.put("Host", "wljy.whut.edu.cn");
        headers1.put("Origin", "https://wljy.whut.edu.cn");
        headers1.put("Pragma", "no-cache");
        headers1.put("Referer", "https://wljy.whut.edu.cn/permissionManager.action?moduleId=PERMISION");
        headers1.put("Sec-Fetch-Dest", "empty");
        headers1.put("Sec-Fetch-Mode", "cors");
        headers1.put("Sec-Fetch-Site", "same-origin");
        headers1.put("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36 Edg/131.0.0.0");
        headers1.put("X-Requested-With", "XMLHttpRequest");
        headers1.put("sec-ch-ua", "\"Microsoft Edge\";v=\"131\", \"Chromium\";v=\"131\", \"Not_A Brand\";v=\"24\"");
        headers1.put("sec-ch-ua-mobile", "?0");
        headers1.put("sec-ch-ua-platform", "\"Windows\"");

        // 自定义请求体（你可以根据实际需求调整）
        String requestBody1 = "id=ptype_-1&pId=SUPPER_PERMISSION_NODE&value=";

        // 发送 POST 请求
        String response1 = sendPostRequest(url, headers1, requestBody1);


        // 尝试解析为 JsonElement，因为返回的数据可能是对象也可能是数组
        ArrayList<Role> roles = objectMapper.readValue(response1, new TypeReference<ArrayList<Role>>() {
        });
        return roles;
    }

    /**
     * 发送 POST 请求的方法
     * @param urlString 请求的 URL
     * @param headers   自定义请求头
     * @param requestBody 请求体
     * @return 响应内容
     * @throws Exception
     */
    public static String sendPostRequest(String urlString, Map<String, String> headers, String requestBody) throws Exception {
        // 创建 URL 对象
        URL url = new URL(urlString);

        // 打开连接
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        // 设置请求方法为 POST
        connection.setRequestMethod("POST");

        // 设置请求头
        for (Map.Entry<String, String> header : headers.entrySet()) {
            connection.setRequestProperty(header.getKey(), header.getValue());
        }

        // 启用写入请求体
        connection.setDoOutput(true);

        // 写入请求体数据
        try (DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream())) {
            outputStream.writeBytes(requestBody);
            outputStream.flush();
        }

        // 获取响应代码
        int responseCode = connection.getResponseCode();
//        System.out.println("响应代码: " + responseCode);

        // 读取响应头
//        System.out.println("响应头信息：");
//        Map<String, List<String>> responseHeaders = connection.getHeaderFields();
//        for (Map.Entry<String, List<String>> entry : responseHeaders.entrySet()) {
//            System.out.println(entry.getKey() + ": " + entry.getValue());
//        }

        // 读取响应数据
        BufferedReader reader;
        if (responseCode >= 200 && responseCode < 300) {
            // 正常响应
            reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        } else {
            // 错误响应
            reader = new BufferedReader(new InputStreamReader(connection.getErrorStream()));
        }

        StringBuilder response = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            response.append(line);
        }
        reader.close();

        // 关闭连接
        connection.disconnect();

        // 返回响应数据
        return response.toString();
    }
}

